import React from 'react';
import {Input, Select, Form, Box, Button, Card, DatePicker, Message, Radio, Upload, Switch, Dialog } from '@alifd/next';
import styles from './index.module.scss';
import {detail, add} from '@/api/ExamPaperAPI'
import {upLoadImage} from '@/api/CommonAPI'
const FormItem = Form.Item;
const formItemLayout = {
  colSpan: 12,
};

const formItemLayout_two = {
    colSpan: 6,
};
const formItemLayout_three = {
    colSpan: 4,
};

// 课程类型，0：自考，1：软考
const courseTypesData = [
    {value: "0", label:"自考"},
    {value: "1", label:"软考"}
  ];
// 课程状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
const courseStatesData = [
    {value:'', label:"请选择"},
    {value:'0', label:"正常"},
    {value:'1', label:"停用"},
    {value:'2', label:"已发布"},
    {value:'3', label:"已下架"}
  ];
const DEFAULT_DATA = {
    id: '',
    examPaperName:'',
    smallName:'',
    examPaperCode:'',
    sort:'',
    type:'0',
    state:'0',
    logoUrl:'',
    logoUrlId:'',
  };

class AddExamPaper extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            postData: DEFAULT_DATA,
            visible: false,
            courseTypesData: courseTypesData,
            imageData:[],
            stateV:'',
            courseOptionList: [],
        };
    }
    // 初始化方法
    componentDidMount(){
        this.props.onRef(this)
    };

    // 1 打开弹框
    onOpen = (courseOption) => {
        this.resetForm(); 
        for(const i in courseStatesData){
            const state = courseStatesData[i]
            if(state.value =='0'){
                this.state.stateV = state.label
                break
            }
        }
        this.setState({
            postData: DEFAULT_DATA,
            courseOptionList: courseOption,
            visible: true,
        })
    };
    // 2 关闭弹框
    onClose = () => {
        this.setState({
            visible: false
        })
    };
    // 3 修改表单信息
    formChange = values => {
        this.setState({
            postData: values
        })
    };
    /**
     * 上传附件
     * @param {*} info 
     */
    upLoadImageBegin = (info) => {
        // 1 调用上传API
        upLoadImage( 'file', info.file).then((data)=>{
            // 2 赋值URL和ID
            if(data){
                DEFAULT_DATA.logoUrl = data.url
                DEFAULT_DATA.logoUrlId = data.id
                // 4 回显信息
                let onSuccessInfo = {
                    success: true,
                    url: data.url,
                }
                info.onSuccess(onSuccessInfo);
            }else{
                info.onError(info.file, "上传失败")
            }
        });
    };
    // 删除图片信息
    onRemoveImage =() =>{
        DEFAULT_DATA.logoUrl = null
        DEFAULT_DATA.logoUrlId = null
        this.setState({
            postData: DEFAULT_DATA
        })
    }
    // 提交表单信息
    onSubmit = (values, errors) => {
        if (errors) {
          console.log('errors', errors);
          return;
        }
        // 处理上传文件属性
        delete values.file
        values.logoUrl= DEFAULT_DATA.logoUrl;
        values.logoUrlId = DEFAULT_DATA.logoUrlId
        // 处理课程标题和名称、代码
        const item = this.props.getCourseInfo(values.courseId);
        values.courseName = item.name
        values.courseCode = item.code
        // 调用新增用户API接口
        add(values).then((flag)=>{
            if(flag){
                Message.success('提交成功');
                this.resetForm(); // 清空表单源数据
                this.onClose();
                this.props.onFreshList();
            }
        });
    };
    /**
     * 重置表单
     */
    resetForm = ()=>{
        DEFAULT_DATA.examPaperName = '',
        DEFAULT_DATA.smallName = '',
        DEFAULT_DATA.examPaperCode = '',
        DEFAULT_DATA.sort = '',
        DEFAULT_DATA.type = '0',
        DEFAULT_DATA.state = '0',
        DEFAULT_DATA.logoUrl = '',
        DEFAULT_DATA.logoUrlId = '',
        this.setState({
            DEFAULT_DATA,
            imageData:[],
        })
    }
    render(){
        return (
            <div > 
                <Dialog title="新增试卷信息" visible={this.state.visible} footer ={false}  onClose={this.onClose} style={{width: '35%'}} >
                    <Card free className={styles.TwoColumnForm}>
                    <Card.Content>
                        <Form responsive fullWidth value={this.state.postData} labelAlign="top" onChange={this.formChange}>
                            <FormItem   FormItem {...formItemLayout} label="简称" required requiredMessage="必填">
                                <Input placeholder="请输入试卷简称" name="smallName" />
                            </FormItem>
                            <FormItem {...formItemLayout} label="名称" required requiredMessage="必填">
                                <Input placeholder="请输入试卷名称" name="examPaperName" />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="代码" required requiredMessage="必填">
                                <Input placeholder="请输入试卷代码" name="examPaperCode" />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="类型："  required requiredMessage="必填">
                                <Radio.Group name="type"  value={this.state.postData.type} dataSource={this.state.courseTypesData}/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="所属课程">
                                <Select name='courseId' placeholder="选择课程" dataSource= {this.state.courseOptionList || []} hasClear/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="排序" required requiredMessage="必填">
                                <Input placeholder="请输入试卷排序" name="sort" />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="状态" required requiredMessage="必填">
                                <Input value={this.state.stateV}  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="发布时间">
                                <Input name="publishTime" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传试卷封面：">
                                <Upload name="file" listType="image" shape="card" limit={1}
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveImage}
                                    defaultValue={this.state.imageData}
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="备注">
                                <Input.TextArea placeholder="请输入备注" name="remark" />
                            </FormItem>
                            <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                                <Box spacing={8} direction="row" align="center">
                                    <Form.Submit type="primary" onClick={this.onSubmit} validate>提交</Form.Submit>
                                    <Button onClick={this.onClose} type="secondary">取消</Button>
                                </Box>
                            </FormItem>
                        </Form>
                    </Card.Content>
                    </Card>
                </Dialog>
            </div>
        );
    }
}
export default AddExamPaper;

